<!--  -->
<template>
    <div class="mt-4">
        <div data-tauri-drag-region class="titlebar">

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 rounded-full " id="titlebar-pc">
                <el-icon>
                    <Monitor />
                </el-icon>
            </div>
            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 rounded-full " id="titlebar-refresh">
                <el-icon>
                    <Refresh />
                </el-icon>
            </div>

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 ml-1 rounded-full"
                id="titlebar-minimize">
                <el-icon>
                    <Minus />
                </el-icon>
            </div>

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 ml-1 rounded-full" id="titlebar-close">
                <el-icon>
                    <Close />
                </el-icon>
            </div>
        </div>

        <div class="gradient-border mt-10" id="box">
            <el-input v-model="input" placeholder=""
                class="input-with-select bg-gradient-to-b from-gray-400 to-gray-600"
                style="border-radius: 15px;padding: 0px;" clearable>
                <template #prepend>
                    <el-cascader v-model="select" :options="options" style="width: 115px;padding:0px" />
                </template>

            </el-input>
        </div>
    </div>
</template>

<script>
import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { emit, listen } from '@tauri-apps/api/event'
import { getClient, ResponseType } from '@tauri-apps/api/http';
import _ from 'lodash';
import api from '@/api'
//import { createParser, ParsedEvent, ReconnectInterval } from 'eventsource-parser';
export default {
    data() {
        return {
            open: false,
            debouncedHandleEnter: null,
            jg: "",
            select: ["ChatGPT", "gpt-4-1106-preview"],
            input: "",
            options: [
                {
                    value: '搜索',
                    label: '搜索',
                    children: [
                        {
                            value: '百度',
                            label: '百度',
                        },
                        {
                            value: '谷歌',
                            label: '谷歌',
                        },
                        {
                            value: '必应',
                            label: '必应',
                        }

                    ]
                },
                {
                    value: '计算',
                    label: '计算'
                },
                {
                    value: '翻译',
                    label: '翻译',
                    children: [
                        {
                            value: 'zh',
                            label: '中文',
                        },
                        {
                            value: 'en',
                            label: '英语',
                        },
                        {
                            value: 'es',
                            label: '西班牙语',
                        },
                        {
                            value: 'fr',
                            label: '法语',
                        },
                        {
                            value: 'it',
                            label: '意大利语',
                        },
                        {
                            value: 'de',
                            label: '德语',
                        }
                        ,
                        {
                            value: 'ru',
                            label: '俄语',
                        }
                        ,
                        {
                            value: 'ja',
                            label: '日语',
                        }
                        ,
                        {
                            value: 'ko',
                            label: '韩语',
                        }


                    ]
                },
                {
                    value: 'ChatGPT',
                    label: 'ChatGPT',
                    children: [
                        {
                            value: 'gpt-4-1106-preview',
                            label: '4-1106',
                        },
                    ]
                }
            ],
            messages: [],
            currentMessage: '',
            qmessages: [
                {
                    role: "system",
                    content: "\nYou are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2023-04\nCurrent model: gpt-4-1106-preview\nCurrent time: 2024/1/14 21:51:51\nLatex inline: $x^2$ \nLatex block: $$e=mc^2$$\n\n"
                }
            ],

        };
    },

    components: {},

    computed: {},

    mounted() {
        this.debouncedHandleEnter = _.debounce(this.handleEnter, 500);
        window.addEventListener('keyup', this.debouncedHandleKeyUp);
        document
            .getElementById("titlebar-pc")
            .addEventListener("click", () => this.viewOpen("gpt", "#/gpt"));
        document
            .getElementById("titlebar-refresh")
            .addEventListener("click", () => window.location.reload());
        document
            .getElementById("titlebar-minimize")
            .addEventListener("click", () => appWindow.minimize());

        document
            .getElementById("titlebar-close")
            .addEventListener("click", () => appWindow.close());
        //this.chatgpt();
        listen("input", (event) => {
            if (event.payload.data.c1 == "ChatGPT") {

                this.qmessages.push(event.payload.data.t)
                console.log('this.qmessages', this.qmessages)
            }
        });
        // console.log('import.meta.env.ChatGPT_API_KEY', import.meta.env)
    },
    beforeDestroy() {
        window.removeEventListener('keyup', this.handleGlobalKeyUp);
    },
    created() { },

    methods: {
        debouncedHandleKeyUp(event) {
            if (event.key === 'Enter') {
                this.debouncedHandleEnter();
            }
        },
        handleEnter() {
            console.log('处理回车键');
            this.ok();
        },
        ok() {
            console.log("select", this.select)
            console.log("input", this.input)
            if (this.select[0] == "搜索") {
                console.log("搜索", this.select[0] == "搜索")
                var url = "";
                if (this.select[1] == "百度") {
                    url = "https://www.baidu.com/s?wd=" + this.input;
                }
                else if (this.select[1] == "必应") {
                    url = "https://www.bing.com/search?pglt=171&q=" + this.input;
                }
                else if (this.select[1] == "谷歌") {
                    url = "https://www.google.com.hk/search?q=" + this.input;
                }

                //https://www.bing.com/search?pglt=171&q=baidu
                this.SearchOpen(this.select[1], url);
            }
            else if (this.select[0] == "翻译") {
                console.log("翻译", this.select[0] == "翻译")
                this.viewOpen("v", "#/v");
                this.translate();
                setTimeout(() => {
                    emit("v", { data: { c1: "翻译", c2: this.findLabelByValue(this.options, this.select[1]), type: 'primary', s: this.input, t: this.jg } });
                    console.log(1);
                }, 1000); // 例如延迟1秒
            }
            else if (this.select[0] == "计算") {
                console.log("翻译", this.select[0] == "翻译")
                this.viewOpen("v", "#/v");
                this.jg = this.calculate(this.input);
                setTimeout(() => {
                    emit("v", { data: { c1: "计算", c2: "", type: 'success', s: this.input, t: this.jg } });
                    console.log(1);
                }, 1000); // 例如延迟1秒
            }
            else if (this.select[0] == "ChatGPT") {
                console.log(this.select);
                this.viewOpen("gpt", "#/gpt");
                this.chatgpt();


            }
        },
        findLabelByValue(options, targetValue) {
            for (const option of options) {
                if (option.children) {
                    const childOption = option.children.find(child => child.value === targetValue);
                    if (childOption) {
                        return childOption.label;
                    }
                }
            }
            return null; // 如果没有找到匹配项，则返回null
        },
        // SecretId: "AKID2uZ3KNC3g5FBsLZYKsBGWYKrAF6i6E8n",
        // SecretKey: "UAfw0pRwEI8kHbmjSx64qRq55sQnz50l",
        calculate(expression) {
            try {
                // 将中文括号转换为英文括号
                expression = expression.replace(/（/g, '(').replace(/）/g, ')');

                // 清除可能的空格并检查括号是否匹配
                expression = expression.replace(/\s+/g, '');
                if (!this.areParenthesesBalanced(expression)) {
                    return 'Unbalanced parentheses';
                }

                return new Function('return ' + expression)();
            } catch (e) {
                return 'Invalid expression';
            }
        },
        areParenthesesBalanced(expression) {
            let balance = 0;
            for (let char of expression) {
                if (char === '(') balance++;
                if (char === ')') balance--;
                if (balance < 0) return false;
            }
            return balance === 0;
        }
        ,
        async translate() {
            const client = await getClient();
            const response = await client.get('https://zhangteng.cloud/5001/api/mainControllers/GetFY?input=' + this.input + "&target=" + this.select[1], {
                timeout: 30,
                // the expected response type
                responseType: ResponseType.JSON
            });

            console.log(response)
            this.jg = response.data.TargetText;
        },
        async SearchOpen(name, url) {
            console.log("SearchOpen")
            const windowConfig = {
                "label": name,
                "fullscreen": false,
                "maximized": false,
                "resizable": true,
                "title": "zt-win-terminal",
                "width": 1200,
                "height": 800,

                //"decorations": false,
                //"alwaysOnTop": true,
                "transparent": true,
                "theme": "Dark",
                "center": true,
                "url": url
            }
            const w = WebviewWindow.getByLabel(name);

            if (w != null) {
                console.log(w);
                await w.setFocus();
            }
            else {
                const webview = new WebviewWindow(name, windowConfig);

                webview.once("tauri://created", function () {
                    // webview window successfully created
                    // 窗口创建成功 打印1
                    console.log(window.screen.height);
                    webview.setPosition(new LogicalPosition(10, window.screen.height - 120));
                });
                webview.once("tauri://error", function (e) {
                    // an error happened creating the webview window
                    // 窗口创建失败 打印2
                    console.log(e);
                });
                let that = this;
                webview.once("tauri://close-requested", function (e) {

                });
            }
        },
        async viewOpen(name, url) {
            console.log("SearchOpen")
            const windowConfig = {
                "label": name,
                "fullscreen": false,
                "maximized": false,
                "resizable": true,
                "title": "zt-win-terminal",
                "width": 500,
                "height": 600,
                "x": 20,
                "y": window.screen.height - 800,
                "decorations": false,
                "alwaysOnTop": true,
                "transparent": true,
                "theme": "Dark",
                // "center": true,
                "url": url
            }
            const w = WebviewWindow.getByLabel(name);

            if (w != null) {
                console.log(w);
                await w.setFocus();
            }
            else {
                const webview = new WebviewWindow(name, windowConfig);

                webview.once("tauri://created", function () {
                    // webview window successfully created
                    // 窗口创建成功 打印1
                    console.log(window.screen.height);
                    //webview.setPosition(new LogicalPosition(10, window.screen.height - 120));
                });
                webview.once("tauri://error", function (e) {
                    // an error happened creating the webview window
                    // 窗口创建失败 打印2
                    console.log(e);
                });
                let that = this;
                webview.once("tauri://close-requested", function (e) {

                });
            }
        },
        async chatgpt() {
            //console.log('chatgpt')
            try {
                let that = this;
                that.currentMessage = "";
                if (this.qmessages.length == 6) {
                    this.qmessages.shift();
                }
                console.log('that.input', that.input)
                that.qmessages.push({
                    role: "user",
                    content: that.input
                });

                const response = await fetch('https://openai.api2d.net/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer fk213277-Ju5VeebU8fgNiSK89MtA1cYl2aD8Agpy',
                        'Content-Type': 'application/json'
                        // 其他需要的头部信息
                    },
                    body: JSON.stringify({

                        messages: this.qmessages,
                        model: that.select[1],
                        // presence_penalty: 0,
                        stream: true,

                        top_p: 1,
                        temperature: 0.3,
                        presence_penalty: 0.6,
                        frequency_penalty: 0
                        //session_id: new Date()
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                //console.log(response)
                const reader = response.body.getReader();
                const list = [];
                that.qmessages.push({
                    role: "assistant",
                    content: that.currentMessage
                });
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) {
                        console.log('done.');
                        //console.log(list);
                        sessionStorage.setItem("qmessages", JSON.stringify(that.qmessages));
                        console.log('this.qmessages', this.qmessages)
                        emit("done", that.qmessages);
                        break; // 读取完毕
                    } else {
                        const dataText = new TextDecoder().decode(value);
                        const data = dataText.split('\n\n').filter(Boolean);
                        // console.log('message: ', new TextDecoder().decode(value));
                        // console.log(data);
                        //console.log('list', list)
                        data.forEach(function (element) {
                            if (element.startsWith('data: ') && !element.includes("[DONE]")) {

                                var line = JSON.parse(element.replace('data: ', ''));
                                //console.log(line);
                                if (line.choices[0].delta.role != "assistant" && line.choices[0].delta.content != null && line.choices[0].delta.content != "") {

                                    that.currentMessage += line.choices[0].delta.content;

                                    list.push(that.currentMessage);
                                    that.qmessages[that.qmessages.length - 1].content = that.currentMessage;
                                    //setTimeout(() => {
                                    emit("gpt", that.qmessages);

                                    //}, 1000); // 例如延迟1秒
                                }
                            }
                        });
                        console.log('that.currentMessage', that.currentMessage)
                        // list.forEach(function (element) {
                        //     if (element.choices[0].delta.role != "assistant" && element.choices[0].delta.content != null) {
                        //         that.currentMessage += element.choices[0].delta.content;
                        //     }

                        // });
                        //console.log(that.currentMessage);

                        // var data = new TextDecoder().decode(value);
                        // this.messages.push(data.data.choices[0].delta.content);
                    }
                }



                //that.jg = that.currentMessage;





            } catch (error) {
                console.error('请求失败:', error);
                this.answer = '无法获取回答';
            }
        },


        addMessage(content) {
            if (content.trim()) {
                this.messages.push({ id: Date.now(), content });
            }
        }
    }
}

</script>
<style lang='scss'>
#box {

    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-family: 'Raleway';
    font-size: 2.5rem;
    padding: 10px;
}


.el-popper {
    top: 0px !important;
    left: 0px !important;
}

.el-input-group__prepend {
    padding: 0px !important;
}

.el-input__wrapper {
    padding: 0px !important;
}

.el-input__inner {
    padding-left: 5px !important;
}

.gradient-border {
    --borderWidth: 1px;

    position: relative;
    border-radius: 8px;
}

.gradient-border:after {
    content: '';
    position: absolute;
    top: calc(-1 * var(--borderWidth));
    left: calc(-1 * var(--borderWidth));
    height: calc(100% + var(--borderWidth) * 1);
    width: calc(100% + var(--borderWidth) * 1);
    background: linear-gradient(60deg, #f79533, #f37055, #ef4e7b, #a166ab, #5073b8, #1098ad, #07b39b, #6fba82);
    border-radius: 15px;
    z-index: -1;
    animation: animatedgradient 3s ease alternate infinite;
    background-size: 300% 300%;
}


@keyframes animatedgradient {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}
</style>